﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.IdentityModel;
using Microsoft.SharePoint.IdentityModel.Pages;
using System.IdentityModel.Tokens;
using Microsoft.SharePoint.Administration.Claims;
using Microsoft.SharePoint.Utilities;
using Microsoft.IdentityModel.Claims;
using Microsoft.SharePoint.Administration;

namespace WindowsSignInPage
{
    public class Default : IdentityModelSignInPageBase
    {
        const string Sp2010_WindowsSignedIn = "SP2010_WindowsSignedIn";
        const string Sp2010_KeepSessionAuthenticated = "WSS_KeepSessionAuthenticated";
        const string Sp2010_AnonymousAccessCookie = "MSOWebPartPage_AnonymousAccessCookie";

        protected EncodedLiteral ClaimsFormsPageTitle;
        protected EncodedLiteral ClaimsFormsPageTitleInTitleArea;
        protected EncodedLiteral ClaimsFormsPageMessage;
        protected TextBox txtUserName;
        protected TextBox txtPassword;
        protected Literal litScript;
        SiteConfig config = SiteConfig.Load();
        protected string SharePointUrl
        {
            get
            {
                //return string.Format("http://{0}:{1}", Context.Request.Url.Host, Context.Request.Url.Port);
                return config.ApplicationUrl;
            }
        }

        protected void InitPage()
        {
            ClaimsFormsPageTitle.Text =
               SPHttpUtility.NoEncode((string)HttpContext.GetGlobalResourceObject("wss", "login_pagetitle", System.Threading.Thread.CurrentThread.CurrentUICulture));
            ClaimsFormsPageTitleInTitleArea.Text =
                SPHttpUtility.NoEncode((string)HttpContext.GetGlobalResourceObject("wss", "login_pagetitle", System.Threading.Thread.CurrentThread.CurrentUICulture));
            if (!this.Request.IsSecureConnection)
            {
                ClaimsFormsPageMessage.Text = "The windows account should be input again to access to your shared driver for the first time. When you changed your password, the input page will show again.";
                    //SPHttpUtility.NoEncode((string)HttpContext.GetGlobalResourceObject("wss", "SSL_warning", System.Threading.Thread.CurrentThread.CurrentUICulture));
            }
        }

       

        protected void Page_Load(object sender, EventArgs e)
        {
            InitPage();

            string currentUser = Authentication.GetCurrentUser();
            if (string.IsNullOrEmpty(currentUser))
            {
                string logonUrl = Authentication.GetLogonUrl();
                //litScript.Text = string.Format("<script type=\"text/javascript\"> window.location.href = '{0}' </script>", logonUrl);
                //SPUtility.Redirect(logonUrl, SPRedirectFlags.Trusted, null);
                Response.Redirect(logonUrl);
            }

            if (!UserExist(currentUser))
            {
                Response.Write(HttpUtility.HtmlDecode(config.NOPermission));
                Response.End();
            }
            //else
            //{
            //    LoginUser user = new LoginUser(currentUser);
            //    UserAutoLogin(user.LoginId, user.Domain, EncryptTool.Decrypt(user.Pwd));
            //}
                            
         }

        protected void LoginBtn_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUserName.Text) || string.IsNullOrEmpty(txtPassword.Text))
            {
                ClaimsFormsPageMessage.Text = "Please input UserName & Password!";
                return;
            }
            string[] userString = txtUserName.Text.Trim().Split('\\');
            string username = string.Empty;
            string domain = string.Empty;
            string password = txtPassword.Text.Trim();

            if (userString.Length > 1)
            {
                domain = userString[0];
                username = userString[1];
            }
            else
            {
                domain = "ceibs.edu";
                username = userString[0];
            }
            UserAutoLogin(username,domain,password);
        }

        protected void UserAutoLogin(string username, string domain, string password)
        {
            if (WindowsContext.Instance.ImpersonateValidUser(username, domain, password))
            {
                try
                {
                    LoginUser loginUser = new LoginUser()
                    {
                        LoginId = username,
                        Domain = domain,
                        Pwd = EncryptTool.Encrypt(password),
                        Comments = "",
                        IsActive = true
                    };
                    loginUser.Save();
                    Authentication.SuccessLogin(username, password);
                    RedirectToSuccessUrl();
                }
                catch (Exception ex)
                {
                    Logger.Error("Login failed!", ex);
                }

                //SPUtility.Redirect("/_windows/default.aspx", SPRedirectFlags.Default, Context);
            }
            else
            {
                ClaimsFormsPageMessage.Text = "The server could not sign you in. Make sure your user name and password are correct, and then try again. ";
            }
        }

        protected bool UserExist(string currentUser)
        {
            bool result = false;
            string admin = "moss2010";
            LoginUser loginUser = new LoginUser(admin);
            string password = EncryptTool.Decrypt(loginUser.Pwd);

            try
            {
                if (WindowsContext.Instance.ImpersonateValidUser(loginUser.LoginId, loginUser.Domain, password))
                {
                    Authentication.SuccessLogin(loginUser.LoginId, password);
                    using (SPSite site = new SPSite(SharePointUrl))
                    {
                        SPWeb web = site.OpenWeb();
                        
                        for (int i = 0; i < web.Users.Count; i++)
                        {
                            SPUser user = web.Users[i];
                            if (user.Name.ToLower().Contains(currentUser.ToLower()))
                            {
                                result = true;
                                break;
                            }
                        }

                        for (int i = 0; i < web.SiteUsers.Count; i++)
                        {
                            SPUser user = web.SiteUsers[i];
                            if (user.Name.ToLower().Contains(currentUser.ToLower()) 
                                && user.Groups.Count>0)
                            {
                                result = true;
                                break;
                            }
                        }
                        
                    }
                }
            }
            finally
            {
                Authentication.RemoveCookiesAndSignOut();
            }
            return result;
            
        }
    }
}